<template>
  <div class="app-container">
    <div class="table_container">
      <div class="table_top_btn">
        <div class="left_btn">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="openAddOrEdit(['allot', 'add'], {})"
            >{{ t("button.add") }}</el-button
          >
        </div>

        <right-toolbar
          ref="rightToolBarRef"
          @queryTable="queryList"
          :searchConfig="searchConfig"
          :columns.sync="columns"
          @search="handleSearch"
        >
        </right-toolbar>
      </div>

      <div class="table_area">
        <el-table
          height="100%"
          v-loading="loading"
          :data="allotData"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            :label="t('tableColumns.operation')"
            align="center"
            fixed
            width="240"
          >
            <template #default="{ row }">
              <div class="operate_link_btn">
                <el-link
                  type="primary"
                  :underline="false"
                  :icon="Document"
                  :disabled="
                    row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                      ? false
                      : true
                  "
                  @click="startApply(row)"
                  >{{ t("button.apply") }}</el-link
                >
                <el-link
                  type="warning"
                  :underline="false"
                  :icon="Edit"
                  @click="openAddOrEdit(['allot', 'edit'], row)"
                  :disabled="
                    row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                      ? false
                      : true
                  "
                  >{{ t("button.edit") }}</el-link
                >
                <el-link
                  type="danger"
                  :underline="false"
                  :icon="Delete"
                  @click="revokeAllot(row)"
                  :disabled="row.enableFlag == 1 || row.enableFlag == 4 ? false : true"
                  >{{ t("button.void") }}</el-link
                >
              </div>
            </template>
          </el-table-column>
          <template v-for="(item, index) in columns" :key="item.key">
            <el-table-column
              v-if="item.visible"
              :prop="item.prop"
              :label="t(`tableColumns.${item.langKey}`)"
              :width="item.width"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <div
                  v-if="item.prop == 'allotNo'"
                  :style="{
                    color: colors.primaryColor,
                    cursor: item.isclick ? 'pointer' : '',
                  }"
                  @click="openAddOrEdit(['allot', 'detail'], row)"
                >
                  {{ row.allotNo }}
                </div>

                <el-tag
                  v-else-if="item.prop == 'enableFlag'"
                  :type="
                    row.enableFlag == 0 || row.enableFlag == 3 || row.enableFlag == 4
                      ? 'danger'
                      : row.enableFlag == 1
                      ? 'warning'
                      : row.enableFlag == 2
                      ? 'primary'
                      : 'success'
                  "
                  >{{
                    filterStatus(row.enableFlag, "documentStatus", "id", "langKey") ||
                    "无"
                  }}</el-tag
                >
                <span v-else-if="item.prop == 'createDate' || item.prop == 'allotDate'">
                  {{ parseTime(row[item.prop], "{y}-{m}-{d} ") || "无" }}
                </span>
                <span v-else>{{ row[item.prop] || "无" }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div class="pagination-area">
        <pagination
          :total="page.total"
          v-model:page="page.pageNum"
          v-model:limit="page.pageSize"
          @pagination="queryList"
        />
      </div>
      <addOrEdit
        v-if="operate.openObj.visible"
        ref="addOrEditDialogRef"
        v-model:add-edit-info="operate"
        @getCanUseAssetsData="queryCanUseAssetsData"
        @submitAddEditInfo="submit"
        @cancelAddEditInfo="cancel"
      ></addOrEdit>
    </div>
  </div>
</template>

<script setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import colors from "@/assets/styles/variables.module.scss";
import { Edit, Document, Delete } from "@element-plus/icons-vue";
import RightToolbar from "@/components/RightToolbar";

import addOrEdit from "@/components/AshDialog/addOrEdit.vue";
import { assetsColums, allotColums } from "@/utils/table/columns";
import {
  GetAssetAllotList,
  AddAssetsAllot,
  getAssetsAllotDetail,
  getAssetsCanAllot,
  AllotAssetsRevoke,
} from "@/api/assetsManage/allot";
import { AddDocumentApply } from "@/api/assetsManage/apply";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import { GetUserInfoAll } from "@/api/sys/user";
import { getUserInfo } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
import { documentStatus } from "@/utils/statuData";
const { AssetClassification } = proxy.useDict("AssetClassification");

const allotData = ref([]); //调拨列表
const loading = ref(false);
const columns = allotColums;
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
});
const users = ref([]);
const organizes = ref([]);
const selectedOrganization = ref(null);
const dates = ref(proxy.getDefault30DaysRange());
//搜索相关
const searchConfig = ref({
  form: {
    Dates: dates.value ? dates.value : ["", ""],
  },
  formItems: [
    {
      label: t("assetsList.assetCode"),
      prop: "assetsCode",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetCodePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetName"),
      prop: "assetsName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetNamePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetType"),
      prop: "assetsClassifyId",
      type: "el-select",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetTypePlaceholder"),
      },
      options: AssetClassification,
      optionProps: {
        key: "dictionaryKey",
        label: "dictionaryName",
        value: "dictionaryCode",
      },
      events: {},
    },
    {
      label: t("assetsList.model"),
      prop: "specModel",
      type: "el-input",
      attrs: { clearable: true, placeholder: t("assetsList.modelPlaceholder") },
    },
    {
      label: t("assetsList.useUser"),
      prop: "useUserName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.userInputPlaceholder"),
      },
      events: {},
    },
    {
      label: t("assetsAllot.allotDate"),
      prop: "Dates",
      type: "el-date-picker",
      attrs: {
        valueFormat: "YYYY-MM-DD",
        "range-separator": t("common.to"),
        "start-placeholder": t("common.startDate"),
        "end-placeholder": t("common.endDate"),
        clearable: true,
        type: "daterange",
        "default-time": dates.value,
      },
    },
  ],
  rules: {},
});

const canUseAssetsInfo = reactive({
  data: [],
  page: {
    total: 0,
    pageNum: 1,
    pageSize: 100,
  },
  loading: false,
  searchInfo: searchConfig,
}); // 传给孙组件的资产数据
provide("canUseAssetsInfo", canUseAssetsInfo);

//组织点击获取人员
const useOrganizationNodeClick = (node) => {
  selectedOrganization.value = node;
  operate.formInfo.useOrganizationId = selectedOrganization.value.value;
  operate.formInfo.useUserId = null;
  queryAllUsers(operate.formInfo.useOrganizationId);
  proxy.$refs["addOrEditDialogRef"].$refs["useOrganizationTreeSelect"][0].blur();
};

const operate = reactive({
  openObj: {
    visible: false,
    openKey: "", //add edit detail
    openType: "", //维修 报废 退还 领用....
    openTitle: "",
    tableTitle: "",
    addLoading: false, //防止重复提交
    state: 0, //0添加 1 修改 2 删除
  },
  formInfo: {
    calloutOrganizationId: "",
    callinOrganizationId: "",
    useOrganizationId: "",
    useUserId: null,
    allotDate: "",
    allotRemark: "",
  },
  formItems: [
    {
      label: t("assetsAllot.allotOutOrganization"),
      prop: "calloutOrganizationId",
      type: "el-tree-select",
      span: 12,
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        disabled: true,
        placeholder: t("assetsAllot.allotOutOrganizationPlaceholder"),
        disabled: true,
      },
      options: organizes,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("assetsAllot.allotOutOrganizationRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("assetsAllot.allotInOrganization"),
      prop: "callinOrganizationId",
      type: "el-tree-select",
      span: 12,
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        placeholder: t("assetsAllot.allotInOrganizationPlaceholder"),
      },
      options: organizes,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("assetsAllot.allotInOrganizationRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("assetsAllot.allotInUseOrganization"),
      prop: "useOrganizationId",
      type: "el-tree-select",
      span: 12,
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        placeholder: t("assetsAllot.allotInUseOrganizationPlaceholder"),
      },
      options: organizes,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {
        "node-click": (node) => useOrganizationNodeClick(node),
      },
      rules: [
        {
          required: true,
          message: t("assetsAllot.allotInUseOrganizationRuleErrorTip"),
          trigger: "change",
        },
      ],
      ref: "useOrganizationTreeSelect",
    },
    {
      label: t("assetsAllot.allotInUser"),
      prop: "useUserId",
      type: "el-select",
      span: 12,
      attrs: { placeholder: t("assetsAllot.allotInUserPlaceholder") },
      options: users,
      optionProps: {
        key: "userId",
        label: "userName",
        value: "userId",
      },
      filterable: true,
      events: {},
      rules: [
        {
          required: true,
          message: t("assetsAllot.allotInUserRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("assetsAllot.allotDate"),
      prop: "allotDate",
      ref: "allotDateRef",
      type: "el-date-picker",
      span: 12,
      attrs: {
        type: "date",
        "value-format": "YYYY-MM-DD",
        "disabled-date": (date) => proxy.dateBeforeToday(date),
        clearable: false,
        disabled: true,
        placeholder: t("assetsAllot.allotDatePlaceholder"),
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("assetsAllot.allotDateRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("assetsAllot.allotRemark"),
      prop: "allotRemark",
      type: "el-input",
      span: 24,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("assetsAllot.allotRemarkPlaceholder"),
      },
      events: {},
    },
  ],
  loadingUser: false,
  tableData: [], //表格数据，添加的时候为空，其他情况为查询赋值
  delList: [], //编辑的时候，删除一些资产
});
//1111获取列表
const queryList = () => {
  const { Dates, ...rest } = searchConfig.value.form;
  const [StartDate, EndDate] = Dates || ["", ""];
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...rest,
    StartDate,
    EndDate,
  };
  loading.value = true;
  GetAssetAllotList(params)
    .then((res) => {
      loading.value = false;
      allotData.value = res.output.output;
      page.total = res.output.count;
    })
    .catch((err) => {
      loading.value = false;
    });
};
//获取人员,必须先选择使用组织
const queryAllUsers = (organizeId) => {
  operate.loadingUser = true;
  GetUserInfoAll({
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      users.value = res.output;
      operate.loadingUser = false;
    })
    .catch((err) => {
      users.value = [];
      operate.loadingUser = false;
    });
};

//查询单据详情
const queryAssetsDetail = (allotId) => {
  getAssetsAllotDetail({ allotNo: allotId }).then((res) => {
    operate.tableData = res.output;
  });
};
//222添加修改相关
const openAddOrEdit = (typeKey, row) => {
  const type = typeKey[0];
  const key = typeKey[1];
  const title =
    key == "add"
      ? t("assetsAllot.addAllotDialogTitle")
      : key == "edit"
      ? t("assetsAllot.editAllotDialogTitle")
      : t("assetsAllot.viewAllotDialogTitle");
  operate.openObj = {
    visible: true,
    openKey: key,
    openType: type,
    openTitle: title,
    tableTitle: t("assetsAllot.allotAssets"),
    addLoading: false,
  };

  operate.formInfo = {
    allotDate: proxy.getNowDate(),
    ...row,
    useUserId: row.useUserId || null,
  };
  operate.tableData = [];
  operate.delList = [];
  if (key != "add") {
    queryAssetsDetail(row.allotNo);
    if (row.useOrganizationId) {
      queryAllUsers(row.useOrganizationId);
    }
  }
};

//获取组织
const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      organizes.value = res.output;
    })
    .catch((err) => {});
};

//添加调拨单的提交
const submit = async (info) => {
  const sub = info.infoSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state ? item.state : 0,
    };
  });
  const delSub = info.delSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state,
    };
  });
  if (sub.length == 0) {
    ElMessage({ message: t("common.pleaseSelectAssets"), type: "warning" });
    return;
  }
  operate.openObj.addLoading = true;
  const formAdd = {
    ...info.info,
    createUserId: JSON.parse(getUserInfo()).userId,
    createUser: JSON.parse(getUserInfo()).userName,
  };
  const formEdit = {
    ...info.info,
    updateUserId: JSON.parse(getUserInfo()).userId,
    updateUser: JSON.parse(getUserInfo()).userName,
  };
  let params = {
    Info: operate.openObj.openKey == "add" ? formAdd : formEdit,
    InfoSub: operate.openObj.openKey == "add" ? sub : sub.concat(delSub),
  };
  const msg = operate.openObj.openKey == "add" ? t("button.add") : t("common.cancel");
  try {
    await AddAssetsAllot(params).then((res) => {
      ElMessage({
        message: `${t("assetsAllot.allotDocument")}:${res.output}${msg}${t(
          "common.success"
        )}`,
        type: "success",
      });
    });
    await cancel();
    await queryList();
  } catch (error) {
    operate.openObj.addLoading = false;
  }
};
//取消添加
const cancel = () => {
  operate.openObj.visible = false;
};
//重新申请
const startApply = (row) => {
  const params = {
    fieldNo: row.allotNo,
    fieldType: 3,
  };
  AddDocumentApply(params)
    .then((res) => {
      console.log(res);
      ElMessage({
        message: t("message.approvalStartedSuccess"),
        type: "success",
      });
      queryList();
    })
    .catch((err) => {
      console.error(err);
    });
};
//作废调拨单
const revokeAllot = (row) => {
  const params = {
    allotNo: row.allotNo,
    userId: JSON.parse(getUserInfo()).userId,
  };
  ElMessageBox.confirm(
    `${t("message.confirmVoidDocument")}:${row.allotNo}`,
    t("message.tip"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }
  )
    .then(() => {
      AllotAssetsRevoke(params)
        .then((res) => {
          ElMessage({ message: t("message.voidSuccess"), type: "success" });
          queryList();
        })
        .catch((err) => {});
    })
    .catch(() => {});
};
///3333高级搜索的
//确定高级搜索
const handleSearch = async (info) => {
  await queryList();
};

//44444444孙组件的列表数据
//获取可调拨资产
const queryCanUseAssetsData = () => {
  if (!operate.formInfo.calloutOrganizationId) {
    ElMessage({ message: t("assetsAllot.allotConfirmTip"), type: "warning" });
    proxy.$refs["addOrEditDialogRef"].canUseAddInfo.openObj.visible = false;
    return;
  }
  canUseAssetsInfo.loading = true;
  let params = {
    pagination: canUseAssetsInfo.page.pageNum - 1,
    pageRow: canUseAssetsInfo.page.pageSize,
    isInit: true,
    enableFlag: 99,
    ...canUseAssetsInfo.searchInfo.form,
    ownershipOrganizationalId: operate.formInfo.calloutOrganizationId,
  };
  getAssetsCanAllot(params)
    .then((res) => {
      canUseAssetsInfo.data = res.output.output;
      canUseAssetsInfo.page.total = res.output.count;
      canUseAssetsInfo.loading = false;
    })
    .catch(() => {
      canUseAssetsInfo.data.value = [];
      canUseAssetsInfo.loading = false;
    });
};

onMounted(() => {
  queryList();
  queryOrganization();
});
</script>
<style lang="scss" scoped></style>
